import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import { Row, Col, Card, Icon, Tooltip, Form, Button, Progress, Tabs, Select, Input, Table, Spin, Checkbox, Radio, message, Modal } from 'antd';
import styles from "./similarAsk.less";
import bulb from '@/assets/medicalKnowledge/灯泡.png';
import { faTshirt } from '@fortawesome/fontawesome-free-solid';

const { Option } = Select;
const Search = Input.Search;
const FormItem = Form.Item;

class AbnormalQ extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ProgressName: '',
      totala: '',
      Selectpd: 'false', // false 为未忽略 true 为已忽略
      Selectcc: false, // 是否忽略传参
      login: false,
      searchKeys: '',
      page: 1,
      pageSize: 10,
      similarList: [],
      value: '',
      value1: '',
      judgeMobile: '',
      judgeMobiles: '',
      frompd: 1,
      // 关联参数
      field: 'q',
      query: '',
      pageA: '',
      pageSizeA: '',
      id: '', // 上下文参数
      loginjqr: false,
      zuid: '',
      shutRelevance: false,
      showModel1: false,
      numberRadio: '1',
      pageSizetwo: 10,
      pagetwo: 1,
      nodeId: '',
      close: false,
      qaId: "",
      isUpdate: false,
      aALeng: '',
      glLeng: 10,
      questiona: '',
      total: 0,
      fromQaSId: '',
      fromQue: '',
      taskResultId: ''
    };
  }

  componentDidMount() {
    const { Selectcc, pageSize, page, searchKeys } = this.state
    this.similarAskList(Selectcc, pageSize, page, searchKeys)
    // this.getAbnormalList(Selectcc, pageSize, page, searchKeys)
  }

  componentDidUpdate() {

  }


  componentWillReceiveProps(nextProps, nextContext) {
    console.log(nextProps, nextContext)

    if (nextProps.ProgressName !== this.state.ProgressName) {
      this.setState({ ProgressName: nextProps.ProgressName })
    }
    if (nextProps.ProgressName == 2) { // 列表清空
      this.setState({ Selectpd: 'false', similarList: [], ProgressName: nextProps.ProgressName,totala:0 })
      this.props.totala2(0)
    }
    if (nextProps.ProgressName == 1) { // 恢复数据
      // this.setState({ totala: 0 })
      if (this.state.ProgressName !== nextProps.ProgressName) {
        this.setState({ Selectcc: false, page: 1, pageSize: 10, searchKeys: '' }, () => {
          const { Selectcc, pageSize, page, searchKeys } = this.state
          this.similarAskList(Selectcc, pageSize, page, searchKeys)
        })
        this.props.totala2(this.state.totala)
        this.setState({ ProgressName: nextProps.ProgressName }, () => {
          console.log('111')
        })
      }
    }
  }

  SelectValue = value => {
    console.log(`选择器 ${value}`);
    if (value === 'false') {
      this.setState({ Selectcc: false }, () => {
        const { Selectcc, pageSize, page, searchKeys } = this.state
        this.similarAskList(Selectcc, pageSize, page, searchKeys)
      })
    }
    if (value === 'true') {
      this.setState({ Selectcc: true }, () => {
        const { Selectcc, pageSize, page, searchKeys } = this.state
        this.similarAskList(Selectcc, pageSize, page, searchKeys)
      })
    }

  }

  append = (item) => {
    console.log('添加到按钮', item)
    const { value, value1, judgeMobile, judgeMobiles } = this.state
    if (judgeMobile === item.questions[value] || judgeMobiles === item.stds[value1]) {
      let from = {}
      from.ques = item.questions[value]
      from.sid = item.sids[value]
      let toStdId = item.sids[value1]
      this.setState({ login: true })
      const { dispatch, currentUser } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'medicalKnowledge/movingSimilarQuestions',
          payload: { from, toStdId },
          callback: res => {
            console.log('移动相似问', res)
            if (res.statue === 'success') {
              message.success(`${res.msg}`)
            }
            this.setState({
              login: false,
            }, () => {
              const { Selectcc, pageSize, page, searchKeys } = this.state
              this.similarAskList(Selectcc, pageSize, page, searchKeys) // 刷新页面
            })
          },
        });
      });
    } else {
      message.error('无效的移动操作')
    }


  }



  deleteTable = (item) => { // 删除相似问
    console.log(item)

    this.setState({ login: true })
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'medicalKnowledge/deleteAbnormalQuestion',
        payload: { id: item.id },
        callback: res => {
          console.log('删除异常问', res)
          if (res.statue === 'success') {
            message.success(`${res.msg}`)
          }
          this.setState({
            login: false,
          }, () => {
            const { Selectcc, pageSize, page, searchKeys } = this.state
            this.similarAskList(Selectcc, pageSize, page, searchKeys)
          })
        },
      });
    });
  }

  iose = (item) => {
    console.log('忽略按钮', item)
    const { Selectcc } = this.state
    let a = []
    if (Selectcc) {
      a.push(item.id)
      this.ignore(true, a)
    }
    if (Selectcc === false) {
      a.push(item.id)
      this.ignore(false, a)
    }

  }

  ignore = (a, b) => {
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'medicalKnowledge/ignoreAbnormalQuestion',
        payload: { isIgnore: a, _id: b },
        callback: res => {
          console.log('忽略按钮', res)
          if (res.statue === 'success') {
            message.success(`${res.msg}`)
          }
          this.setState({
            login: false,
          }, () => {
            const { Selectcc, pageSize, page, searchKeys } = this.state
            this.similarAskList(Selectcc, pageSize, page, searchKeys)
          })
        },
      });
    });
  }






  // 异常问列表
  similarAskList = (isIgnore, limit = 10, page = 1, searchKeys) => {
    this.setState({ login: true })
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'medicalKnowledge/getAbnormalList',
        payload: { isIgnore, limit, page, searchKeys, },
        callback: res => {
          console.log('异常问列表', res)
          this.setState({
            login: false,
            similarList: res.list,
            totala: res.total
          }, () => {
            this.props.totala2(this.state.totala)
          })
        },
      });
    });
  }



  pageWay = (a) => {
    console.log(a)
    this.setState({ page: a }, () => {
      const { Selectcc, pageSize, page, searchKeys } = this.state
      this.similarAskList(Selectcc, pageSize, page, searchKeys)
    })
  }

  onShowSizepageWay = (a, b) => {
    console.log(a, b)
    this.setState({ page: a, pageSize: b }, () => {
      const { Selectcc, pageSize, page, searchKeys } = this.state
      this.similarAskList(Selectcc, pageSize, page, searchKeys)
    })
  }

  allIgnore = () => { // 全部忽略
    const { similarList, Selectcc } = this.state
    let a = []
    similarList.map((item, index) => {
      a.push(item.id)
    })
    console.log(a)
    if (Selectcc) {
      this.ignore(true, a)
    }
    if (Selectcc === false) {
      this.ignore(false, a)
    }
  }

  //  关联方法
  handleOpen = (row) => {
    this.props.form.setFields({ "businessName": "" })
    console.log(row)
    this.setState({ question: row.question, query: '' }, () => {
      this.AnswerRelevance(
        this.state.robotId,
        this.state.question,
        this.state.field,
        this.state.query,
        1,
        10)
      this.setState({ showModel1: true, fromQaSId: row.sid, fromQue: row.question, taskResultId: row.id })
    })
  }

  // 获取关联列表数据
  AnswerRelevance = (robotIds, question, field, query, page, pageSize) => {
    this.setState({
      logins: true
    })
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'medicalKnowledge/fakeAnswerRelevanceData',
      payload: { robotId: currentUser.robotId, question, field, query, page, limit: pageSize },
      callback: res => {
        console.log(res)
        let aA = res.suggestList
        let bB = res.qaList
        let aALeng = res.suggestList.length
        let bBLeng = res.qaList.length
        console.log(aALeng + bBLeng)
        const total = [...aA, ...bB]
        total.map((item, index) => {
          item['key'] = index
        })
        this.setState({
          total2: res.total,
          qaListTable: total,
          logins: false,
          aALeng: aALeng,
          glLeng: Number(aALeng + bBLeng),

        })
      },
    });
  }

  setClassName = (record, index) => {
    return (index < this.state.aALeng ? styles.red : '')
  }

  handleSubmitComment = (current) => {
    console.log('tcx', current, typeof (current))

    this.AnswerRelevance(
      this.state.robotId,
      this.state.question,
      this.state.field,
      this.state.query,
      current,
      this.state.pageSizetwo
    )

  }

  handleSubmitComments = (a, b) => {
    this.setState({ pageSizetwo: b })
    this.AnswerRelevance(
      this.state.robotId,
      this.state.question,
      this.state.field,
      this.state.query,
      a,
      b
    )
  }

  // 搜索问题
  onFromA = (val) => {
    console.log('fu', val)
    let text;
    if (val === '1') {
      text = 'q'
    }
    if (val === '2') {
      text = 'a'
    }
    this.setState({
      pagetwo: 1,
      pageSizetwo: 10,
      field: text
    })
    setTimeout(() => {
      this.AnswerRelevance(
        this.state.robotId,
        this.state.question,
        this.state.field,
        this.state.query,
        1,
        10)
    })
  }

  // 搜索内容
  onFrom = (val) => {
    console.log('fu', val)
    this.setState({
      pagetwo: 1,
      pageSizetwo: 10,
      query: val,
    }, () => {
      if (val === '') {
        this.AnswerRelevance(
          this.state.robotId,
          this.state.question,
          this.state.field,
          this.state.query,
          1,
          10)
      } else {
        this.AnswerRelevance(
          this.state.robotId,
          val,
          this.state.field,
          this.state.query,
          1,
          10)
      }
    })
  }

  handleDelete = (item) => {
    console.log('item', item)
    this.setState({ shutRelevance: false })
    const { dispatch, currentUser } = this.props;
    const { fromQaSId, fromQue, taskResultId } = this.state
    console.log(fromQaSId, fromQue, taskResultId)
    dispatch({
      type: 'medicalKnowledge/addToOtherQa',
      payload: { id: taskResultId, qaSid: item.sid },
      callback: res => {
        if (res.code === 0) {
          message.success(`${res.msg}`);
          this.setState({ showModel1: false })
          const { Selectcc, pageSize, page, searchKeys } = this.state
          this.similarAskList(Selectcc, pageSize, page, searchKeys)
        }
        console.log('关联异常问', res)
      },
    });
  }


  render() {
    const { getFieldDecorator } = this.props.form;
    const columns1 = [
      {
        title: '问题',
        dataIndex: 'question'
      },
      {
        title: '分类',
        dataIndex: 'category'
      },
      {
        title: '操作',
        render: (text, item) => {
          return <div className={styles.pb}>
            <div className={styles.buttongx} onClick={(text) => { this.handleDelete(item) }}>
              {/* <MyIcon  type="icon-bi" /> */}
              <span><Icon size="small" type="link" style={{ marginRight: 5 }} /></span>
              <span>关联</span>
            </div>
          </div>
        }
      },
    ]
    const columns = [
      {
        title: '异常问法',
        width: 'calc(30vw)',
        dataIndex: 'question',
        render:(item) => {
         return  <div  dangerouslySetInnerHTML={{ __html: item }}></div>
        }

      },
      {
        title: '所属问题的其它问法',
        dataIndex: 'references',
        width: 'calc(30vw)',
        render: (references, items) => {
          return <Row>
            {references.map((item, index) => {
              return <Row style={{ marginBottom: 10 }}>
                <Col span={24}>
                  {item}
                </Col>
              </Row>
            })}
          </Row>

        }
      },

      {
        title: '操作',
        width: 'calc(15vw)',
        dataIndex: '',
        render: (text, item) => {

          if (this.state.Selectcc) {
            // 已忽略
            return <div className={styles.flexBj}>
              <Button style={{ marginRight: 10, marginBottom: 4 }} icon='eye-invisible' size='small' onClick={() => { this.iose(item) }} type='primary'>恢复</Button>
              <div
                style={{ marginRight: 10, marginBottom: 4 }}
                className={styles.buttongl}
                onClick={() => { this.deleteTable(item) }}>
                <span><Icon size="small" type="delete" style={{ marginRight: 5 }} />
                </span><span>删除</span>
              </div>
              <Button
                type='primary'
                icon='link'
                size="small"
                onClick={() => this.handleOpen(item)}>
                关联
            </Button>
            </div>

          } else {
            return <div className={styles.flexBj}>
              <div className='zdyButtonA'> <Button style={{ marginRight: 10, marginBottom: 4 }} icon='eye-invisible' size='small' onClick={() => { this.iose(item) }} type='primary'>忽略</Button></div>
              <div
                style={{ marginRight: 10, marginBottom: 4 }}
                className={styles.buttongl}
                onClick={() => { this.deleteTable(item) }}>
                <span><Icon size="small" type="delete" style={{ marginRight: 5 }} />
                </span><span>删除</span>
              </div>
              <div className='zdyButtonA'>
                <Button
                  type='primary'
                  icon='link'
                  size="small"
                  onClick={() => this.handleOpen(item)}>
                  关联
          </Button>
              </div>
            </div>
          }

        }
      },

    ]
    return (
      <Suspense fallback={< PageLoading />}>
        <div>
          <div className={styles.toptit}>
            {this.state.Selectcc ? <div className='zdyButtonA'><Button onClick={this.allIgnore} type='primary' icon='eye-invisible'>全部恢复</Button></div> : <div className='zdyButtonA'><Button onClick={this.allIgnore} type='primary' icon='eye-invisible'>全部忽略</Button></div>}
            <div>
              {getFieldDecorator('coreword1', {
                initialValue: this.state.Selectpd,
              })(
                <Select style={{ width: 120 }} onChange={this.SelectValue} >
                  <Option value="false">未忽略</Option>
                  <Option value="true">已忽略</Option>
                </Select>
              )}
              <span>&#12288;</span>
              {getFieldDecorator('coreword2', {
                initialValue: '',
              })(
                <Search
                  placeholder="多个关键词用空格隔开"
                  onSearch={value => {
                    this.setState({ searchKeys: value,page: 1 }, () => {
                      const { Selectcc, pageSize, page, searchKeys } = this.state
                      this.similarAskList(Selectcc, pageSize, page, searchKeys)
                    })
                  }}
                  style={{ width: 324 }}
                />
              )}
            </div>
          </div>
          <Spin spinning={this.state.login}>
            <Table
              // className='zdyTable'
              style={{ padding: '20px 0px 0px 0px' }}
              columns={columns}
              dataSource={this.state.similarList}// 数据
              // onChange={this.handleChange}
              pagination={{  // 分页
                total: this.state.totala,
                pageSize: this.state.pageSize,  // 显示几条一页
                current: this.state.page, // 当前页
                showSizeChanger: true,  // 是否显示可以设置几条一页的选项
                showQuickJumper: true,
                onChange: this.pageWay,
                onShowSizeChange: this.onShowSizepageWay
              }}
            />
          </Spin>

          {/* 关联组件 */}
          <Modal
            style={{ top: 60 }}
            width={'calc( 70vw)'}
            className={styles.overa}
            title='添加关联知识点'
            visible={this.state.showModel1}
            footer={null}
            onCancel={() => {
              this.setState({
                showModel1: false
              })
            }}
            onOk={() => { // 确定方法不开出去
              this.setState({
                showModel1: false
              })
            }}
          >

            <Form layout="inline" style={{ paddingBottom: 20 }}>
              <FormItem style={{ marginLeft: 20 }}>

                <Select
                  defaultValue={this.state.numberRadio}
                  style={{ width: 160 }}
                  onChange={this.onFromA}
                >
                  <Option value='1'>搜索问题</Option>
                  <Option value='2'>搜索答案</Option>
                </Select>
              </FormItem>
              <FormItem >
                {getFieldDecorator('businessName', {
                  initialValue: '',
                })(
                  <Search
                    placeholder="请输入搜索内容"
                    onSearch={value => {
                      this.onFrom(value)
                    }}
                    style={{ width: 320 }}
                  />
                )}
              </FormItem>
            </Form>
            <Spin spinning={this.state.logins}>
              <Table
                rowClassName={this.setClassName}
                className={styles.over}
                //  bordered
                columns={columns1}
                dataSource={this.state.qaListTable}
                pagination={{  // 分页
                  total: this.state.total2, // 数据总数量
                  pageSize: this.state.glLeng,  // 显示几条一页
                  defaultPageSize: this.state.pagetwo, // 当前页
                  // showSizeChanger: true,  // 是否显示可以设置几条一页的选项
                  showQuickJumper: true,
                  onChange: this.handleSubmitComment,
                  onShowSizeChange: this.handleSubmitComments
                }}
              />
            </Spin>
          </Modal>
        </div>
      </Suspense >
    );
  }
}

export default connect(({ user }) => ({ // 全局数据
  currentUser: user.currentUser,
}))(Form.create()(AbnormalQ));